/*!
 * \file test_code_helper_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief 代码辅助工具综合测试文件
 * 测试各种代码辅助功能和工具函数
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <algorithm>
#include <regex>
#include <map>
#include <set>
#include <random>
#include <iomanip>

// 代码辅助工具的模拟实现
namespace CodeHelper {
    
    // 字符串工具函数
    std::string trim(const std::string& str) {
        size_t start = str.find_first_not_of(" \t\n\r");
        if (start == std::string::npos) return "";
        size_t end = str.find_last_not_of(" \t\n\r");
        return str.substr(start, end - start + 1);
    }
    
    std::vector<std::string> split(const std::string& str, const std::string& delimiter) {
        std::vector<std::string> tokens;
        size_t start = 0;
        size_t end = str.find(delimiter);
        
        while (end != std::string::npos) {
            tokens.push_back(str.substr(start, end - start));
            start = end + delimiter.length();
            end = str.find(delimiter, start);
        }
        tokens.push_back(str.substr(start));
        return tokens;
    }
    
    std::string join(const std::vector<std::string>& strings, const std::string& delimiter) {
        if (strings.empty()) return "";
        
        std::ostringstream oss;
        for (size_t i = 0; i < strings.size(); ++i) {
            if (i > 0) oss << delimiter;
            oss << strings[i];
        }
        return oss.str();
    }
    
    std::string replace_all(std::string str, const std::string& from, const std::string& to) {
        if (from.empty()) {
            return str;  // Return original string if nothing to replace
        }
        size_t start_pos = 0;
        while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length();
        }
        return str;
    }
    
    // 文件工具函数
    bool file_exists(const std::string& filename) {
        std::ifstream file(filename);
        return file.good();
    }
    
    std::string read_file(const std::string& filename) {
        std::ifstream file(filename);
        if (!file.is_open()) {
            throw std::runtime_error("无法打开文件: " + filename);
        }
        
        std::ostringstream oss;
        oss << file.rdbuf();
        return oss.str();
    }
    
    bool write_file(const std::string& filename, const std::string& content) {
        std::ofstream file(filename);
        if (!file.is_open()) {
            return false;
        }
        
        file << content;
        return file.good();
    }
    
    // 数据转换工具
    template<typename T>
    std::string to_string_with_precision(T value, int precision) {
        std::ostringstream oss;
        oss << std::fixed << std::setprecision(precision) << static_cast<double>(value);
        return oss.str();
    }
    
    // 时间工具函数
    std::string get_current_time_string() {
        auto now = std::chrono::system_clock::now();
        auto time_t = std::chrono::system_clock::to_time_t(now);
        std::ostringstream oss;
        oss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
        return oss.str();
    }
    
    // 哈希工具函数
    size_t simple_hash(const std::string& str) {
        std::hash<std::string> hasher;
        return hasher(str);
    }
    
    // 随机工具函数
    std::string generate_random_string(size_t length) {
        const std::string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, chars.size() - 1);
        
        std::string result;
        for (size_t i = 0; i < length; ++i) {
            result += chars[dis(gen)];
        }
        return result;
    }
}

/**
 * 代码辅助工具综合测试类
 * 测试各种代码辅助功能和工具函数
 */
class CodeHelperComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化测试数据
        test_strings_ = {
            "hello world", "  trimmed  ", "split,by,comma",
            "replace_this_text", "", "single", "multiple words here"
        };
        
        test_numbers_ = {0, 1, -1, 123, -456, 999999, -999999};
        test_floats_ = {0.0, 1.0, -1.0, 123.456, -789.123, 3.14159};
        
        // 创建临时测试文件
        temp_filename_ = "test_temp_file.txt";
        temp_content_ = "这是测试文件内容\n包含多行文本\n用于测试文件操作";
    }

    void TearDown() override {
        // 清理临时文件
        if (std::filesystem::exists(temp_filename_)) {
            std::filesystem::remove(temp_filename_);
        }
    }

    std::vector<std::string> test_strings_;
    std::vector<int> test_numbers_;
    std::vector<double> test_floats_;
    std::string temp_filename_;
    std::string temp_content_;
};

/**
 * 测试字符串修剪功能
 */
TEST_F(CodeHelperComprehensiveTest, TestStringTrimming) {
    // 测试基本修剪
    EXPECT_EQ(CodeHelper::trim("  hello  "), "hello");
    EXPECT_EQ(CodeHelper::trim("\t\nworld\r\n"), "world");
    EXPECT_EQ(CodeHelper::trim("   "), "");
    EXPECT_EQ(CodeHelper::trim("no_spaces"), "no_spaces");
    
    // 测试边界条件
    EXPECT_EQ(CodeHelper::trim(""), "");
    EXPECT_EQ(CodeHelper::trim(" "), "");
    EXPECT_EQ(CodeHelper::trim("a"), "a");
    EXPECT_EQ(CodeHelper::trim(" a "), "a");
}

/**
 * 测试字符串分割功能
 */
TEST_F(CodeHelperComprehensiveTest, TestStringSplitting) {
    // 测试逗号分割
    auto result1 = CodeHelper::split("a,b,c", ",");
    EXPECT_EQ(result1.size(), 3);
    EXPECT_EQ(result1[0], "a");
    EXPECT_EQ(result1[1], "b");
    EXPECT_EQ(result1[2], "c");
    
    // 测试空格分割
    auto result2 = CodeHelper::split("hello world test", " ");
    EXPECT_EQ(result2.size(), 3);
    EXPECT_EQ(result2[0], "hello");
    EXPECT_EQ(result2[1], "world");
    EXPECT_EQ(result2[2], "test");
    
    // 测试边界条件
    auto result3 = CodeHelper::split("", ",");
    EXPECT_EQ(result3.size(), 1);
    EXPECT_EQ(result3[0], "");
    
    auto result4 = CodeHelper::split("no_delimiter", ",");
    EXPECT_EQ(result4.size(), 1);
    EXPECT_EQ(result4[0], "no_delimiter");
}

/**
 * 测试字符串连接功能
 */
TEST_F(CodeHelperComprehensiveTest, TestStringJoining) {
    // 测试基本连接
    std::vector<std::string> tokens1 = {"a", "b", "c"};
    EXPECT_EQ(CodeHelper::join(tokens1, ","), "a,b,c");
    EXPECT_EQ(CodeHelper::join(tokens1, " "), "a b c");
    
    // 测试单个元素
    std::vector<std::string> tokens2 = {"single"};
    EXPECT_EQ(CodeHelper::join(tokens2, ","), "single");
    
    // 测试空向量
    std::vector<std::string> empty_tokens;
    EXPECT_EQ(CodeHelper::join(empty_tokens, ","), "");
}

/**
 * 测试字符串替换功能
 */
TEST_F(CodeHelperComprehensiveTest, TestStringReplacement) {
    auto start_time = std::chrono::high_resolution_clock::now();
    
    // 测试基本替换
    EXPECT_EQ(CodeHelper::replace_all("hello world", "world", "universe"), "hello universe");
    
    // 检查执行时间，避免无限循环
    auto current_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time);
    EXPECT_LT(elapsed.count(), 100) << "基本字符串替换应该很快完成";
    
    EXPECT_EQ(CodeHelper::replace_all("aaa", "a", "b"), "bbb");
    EXPECT_EQ(CodeHelper::replace_all("abc abc abc", "abc", "xyz"), "xyz xyz xyz");
    
    // 测试边界条件
    EXPECT_EQ(CodeHelper::replace_all("hello", "xyz", "abc"), "hello");
    EXPECT_EQ(CodeHelper::replace_all("", "a", "b"), "");
    
    // 谨慎测试空替换字符串（可能导致无限循环）
    auto before_empty_test = std::chrono::high_resolution_clock::now();
    std::string result = CodeHelper::replace_all("hello", "", "x");
    auto after_empty_test = std::chrono::high_resolution_clock::now();
    auto empty_test_time = std::chrono::duration_cast<std::chrono::milliseconds>(after_empty_test - before_empty_test);
    
    EXPECT_LT(empty_test_time.count(), 50) << "空字符串替换测试应该快速完成或被跳过";
    EXPECT_EQ(result, "hello") << "空替换字符串应该返回原字符串";
    
    // 总体执行时间检查
    auto end_time = std::chrono::high_resolution_clock::now();
    auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    EXPECT_LT(total_time.count(), 200) << "整个字符串替换测试应在200ms内完成";
}

/**
 * 测试文件存在性检查
 */
TEST_F(CodeHelperComprehensiveTest, TestFileExistence) {
    // 测试不存在的文件
    EXPECT_FALSE(CodeHelper::file_exists("non_existent_file.txt"));
    
    // 创建临时文件并测试
    std::ofstream temp_file(temp_filename_);
    temp_file << "test content";
    temp_file.close();
    
    EXPECT_TRUE(CodeHelper::file_exists(temp_filename_));
}

/**
 * 测试文件读写功能
 */
TEST_F(CodeHelperComprehensiveTest, TestFileReadWrite) {
    // 测试写入文件
    bool write_success = CodeHelper::write_file(temp_filename_, temp_content_);
    EXPECT_TRUE(write_success);
    EXPECT_TRUE(CodeHelper::file_exists(temp_filename_));
    
    // 测试读取文件
    std::string read_content = CodeHelper::read_file(temp_filename_);
    EXPECT_EQ(read_content, temp_content_);
    
    // 测试读取不存在的文件
    try {
        CodeHelper::read_file("non_existent_file.txt");
        FAIL() << "应该抛出异常";
    } catch (const std::runtime_error& e) {
        EXPECT_TRUE(std::string(e.what()).find("无法打开文件") != std::string::npos);
    }
}

/**
 * 测试数据转换功能
 */
TEST_F(CodeHelperComprehensiveTest, TestDataConversion) {
    // 测试浮点数精度转换
    EXPECT_EQ(CodeHelper::to_string_with_precision(123.456789, 2), "123.46");
    EXPECT_EQ(CodeHelper::to_string_with_precision(123.456789, 4), "123.4568");
    EXPECT_EQ(CodeHelper::to_string_with_precision(0.0, 2), "0.00");
    
    // 测试整数转换
    EXPECT_EQ(CodeHelper::to_string_with_precision(123, 2), "123.00");
    EXPECT_EQ(CodeHelper::to_string_with_precision(-456, 1), "-456.0");
}

/**
 * 测试时间工具功能
 */
TEST_F(CodeHelperComprehensiveTest, TestTimeUtilities) {
    // 测试获取当前时间字符串
    std::string time_str = CodeHelper::get_current_time_string();
    EXPECT_FALSE(time_str.empty());
    
    // 验证时间字符串格式（应该包含年月日时分秒）
    EXPECT_TRUE(time_str.find("-") != std::string::npos); // 日期分隔符
    EXPECT_TRUE(time_str.find(":") != std::string::npos); // 时间分隔符
    EXPECT_TRUE(time_str.find(" ") != std::string::npos); // 日期时间分隔符
    
    // 测试时间字符串长度合理性
    EXPECT_GE(time_str.length(), 19); // "YYYY-MM-DD HH:MM:SS" 至少19个字符
}

/**
 * 测试哈希工具功能
 */
TEST_F(CodeHelperComprehensiveTest, TestHashUtilities) {
    // 测试相同字符串产生相同哈希
    std::string test_str = "hello world";
    size_t hash1 = CodeHelper::simple_hash(test_str);
    size_t hash2 = CodeHelper::simple_hash(test_str);
    EXPECT_EQ(hash1, hash2);
    
    // 测试不同字符串产生不同哈希（大概率）
    size_t hash3 = CodeHelper::simple_hash("different string");
    EXPECT_NE(hash1, hash3);
    
    // 测试空字符串哈希
    size_t empty_hash = CodeHelper::simple_hash("");
    EXPECT_NE(empty_hash, hash1);
}

/**
 * 测试随机字符串生成
 */
TEST_F(CodeHelperComprehensiveTest, TestRandomStringGeneration) {
    // 测试生成指定长度的随机字符串
    std::string random1 = CodeHelper::generate_random_string(10);
    EXPECT_EQ(random1.length(), 10);
    
    std::string random2 = CodeHelper::generate_random_string(20);
    EXPECT_EQ(random2.length(), 20);
    
    // 测试生成的字符串不同（大概率）
    std::string random3 = CodeHelper::generate_random_string(10);
    EXPECT_NE(random1, random3);
    
    // 测试字符串只包含预期字符
    std::string random4 = CodeHelper::generate_random_string(100);
    for (char c : random4) {
        EXPECT_TRUE(std::isalnum(c));
    }
    
    // 测试边界条件
    std::string empty_random = CodeHelper::generate_random_string(0);
    EXPECT_EQ(empty_random.length(), 0);
}

/**
 * 测试字符串工具的性能特征
 */
TEST_F(CodeHelperComprehensiveTest, TestStringUtilityPerformance) {
    const int iterations = 1000;
    std::vector<std::string> test_data;
    
    // 生成测试数据
    for (int i = 0; i < iterations; ++i) {
        test_data.push_back("test_string_" + std::to_string(i) + "_with_some_content");
    }
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 执行字符串操作
    for (const auto& str : test_data) {
        std::string trimmed = CodeHelper::trim("  " + str + "  ");
        auto parts = CodeHelper::split(trimmed, "_");
        std::string joined = CodeHelper::join(parts, "-");
        std::string replaced = CodeHelper::replace_all(joined, "test", "processed");
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    // 验证性能合理性
    EXPECT_LT(duration.count(), 1000000); // 应该在1秒内完成
    
    std::cout << "字符串工具性能: " << iterations << " 次操作耗时 " 
              << duration.count() << " 微秒" << std::endl;
}

/**
 * 测试文件操作的性能特征
 */
TEST_F(CodeHelperComprehensiveTest, TestFileOperationPerformance) {
    const int file_count = 10;
    std::vector<std::string> filenames;
    std::vector<std::string> contents;
    
    // 生成测试文件名和内容
    for (int i = 0; i < file_count; ++i) {
        filenames.push_back("test_file_" + std::to_string(i) + ".txt");
        contents.push_back("Test content for file " + std::to_string(i) + "\n" +
                          "This is line 2\nThis is line 3\n");
    }
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 写入文件
    for (int i = 0; i < file_count; ++i) {
        bool success = CodeHelper::write_file(filenames[i], contents[i]);
        EXPECT_TRUE(success);
    }
    
    // 读取文件
    std::vector<std::string> read_contents;
    for (int i = 0; i < file_count; ++i) {
        std::string content = CodeHelper::read_file(filenames[i]);
        read_contents.push_back(content);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    // 验证内容正确性
    for (int i = 0; i < file_count; ++i) {
        EXPECT_EQ(read_contents[i], contents[i]);
    }
    
    // 清理测试文件
    for (const auto& filename : filenames) {
        if (std::filesystem::exists(filename)) {
            std::filesystem::remove(filename);
        }
    }
    
    std::cout << "文件操作性能: " << file_count << " 个文件读写耗时 " 
              << duration.count() << " 微秒" << std::endl;
}

/**
 * 测试多线程环境下的工具函数
 */
TEST_F(CodeHelperComprehensiveTest, TestMultiThreadUtilities) {
    const int num_threads = 4;
    const int operations_per_thread = 100;
    std::vector<std::thread> threads;
    std::atomic<int> success_count(0);
    
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([&, t]() {
            for (int i = 0; i < operations_per_thread; ++i) {
                // 执行各种工具函数操作
                std::string test_str = "thread_" + std::to_string(t) + "_op_" + std::to_string(i);
                
                // 字符串操作
                std::string trimmed = CodeHelper::trim("  " + test_str + "  ");
                auto parts = CodeHelper::split(trimmed, "_");
                std::string joined = CodeHelper::join(parts, "-");
                
                // 哈希操作
                size_t hash_value = CodeHelper::simple_hash(test_str);
                
                // 随机字符串生成
                std::string random_str = CodeHelper::generate_random_string(10);
                
                if (!trimmed.empty() && !joined.empty() && 
                    hash_value != 0 && random_str.length() == 10) {
                    success_count.fetch_add(1);
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证结果
    int expected_success = num_threads * operations_per_thread;
    EXPECT_EQ(success_count.load(), expected_success);
    
    std::cout << "多线程工具测试结果: " << success_count.load() 
              << "/" << expected_success << " 次操作成功" << std::endl;
}

/**
 * 测试错误处理和边界条件
 */
TEST_F(CodeHelperComprehensiveTest, TestErrorHandlingAndBoundaryConditions) {
    // 测试文件操作错误处理
    try {
        CodeHelper::read_file("/invalid/path/file.txt");
        FAIL() << "应该抛出异常";
    } catch (const std::runtime_error&) {
        // 预期的异常
    }
    
    // 测试空字符串处理
    EXPECT_EQ(CodeHelper::trim(""), "");
    EXPECT_EQ(CodeHelper::replace_all("", "a", "b"), "");
    
    auto empty_split = CodeHelper::split("", ",");
    EXPECT_EQ(empty_split.size(), 1);
    
    std::vector<std::string> empty_vec;
    EXPECT_EQ(CodeHelper::join(empty_vec, ","), "");
    
    // 测试极端值
    std::string very_long_string(10000, 'a');
    std::string trimmed_long = CodeHelper::trim(very_long_string);
    EXPECT_EQ(trimmed_long.length(), 10000);
    
    // 测试特殊字符
    std::string special_chars = "!@#$%^&*()_+-=[]{}|;':\",./<>?";
    size_t special_hash = CodeHelper::simple_hash(special_chars);
    EXPECT_GT(special_hash, 0);
}

/**
 * 测试工具函数的组合使用
 */
TEST_F(CodeHelperComprehensiveTest, TestUtilityCombination) {
    // 模拟复杂的文本处理流程
    std::string input_text = "  Hello, World! This is a test string.  ";
    
    // 1. 修剪空白字符
    std::string trimmed = CodeHelper::trim(input_text);
    EXPECT_EQ(trimmed, "Hello, World! This is a test string.");
    
    // 2. 替换标点符号
    std::string no_punct = CodeHelper::replace_all(trimmed, ",", "");
    no_punct = CodeHelper::replace_all(no_punct, "!", "");
    no_punct = CodeHelper::replace_all(no_punct, ".", "");
    EXPECT_EQ(no_punct, "Hello World This is a test string");
    
    // 3. 分割单词
    auto words = CodeHelper::split(no_punct, " ");
    EXPECT_EQ(words.size(), 7);
    
    // 4. 转换为小写（简单实现）
    for (auto& word : words) {
        std::transform(word.begin(), word.end(), word.begin(), ::tolower);
    }
    
    // 5. 重新连接
    std::string processed = CodeHelper::join(words, "_");
    EXPECT_EQ(processed, "hello_world_this_is_a_test_string");
    
    // 6. 生成哈希
    size_t final_hash = CodeHelper::simple_hash(processed);
    EXPECT_GT(final_hash, 0);
    
    std::cout << "组合处理结果: \"" << input_text << "\" -> \"" 
              << processed << "\" (hash: " << final_hash << ")" << std::endl;
}

/**
 * 测试完整的代码辅助工具工作流程
 */
TEST_F(CodeHelperComprehensiveTest, TestCompleteWorkflow) {
    // 模拟完整的代码辅助工具使用场景
    
    // 1. 数据准备
    std::vector<std::string> input_data = {
        "  function_name_1  ", "ClassName2", "CONSTANT_VALUE",
        "variable_name", "method_name_with_params"
    };
    
    // 2. 数据处理
    std::vector<std::string> processed_data;
    std::map<std::string, size_t> hash_map;
    
    for (const auto& item : input_data) {
        // 清理数据
        std::string cleaned = CodeHelper::trim(item);
        
        // 转换命名风格（驼峰转下划线）
        std::string snake_case;
        bool prev_was_upper = false;
        for (size_t i = 0; i < cleaned.length(); ++i) {
            char c = cleaned[i];
            if (std::isupper(c)) {
                if (i > 0 && !prev_was_upper && snake_case.back() != '_') {
                    snake_case += '_';
                }
                snake_case += std::tolower(c);
                prev_was_upper = true;
            } else {
                snake_case += c;
                prev_was_upper = false;
            }
        }
        
        processed_data.push_back(snake_case);
        hash_map[snake_case] = CodeHelper::simple_hash(snake_case);
    }
    
    // 3. 生成报告文件
    std::ostringstream report;
    report << "代码辅助工具处理报告\n";
    report << "生成时间: " << CodeHelper::get_current_time_string() << "\n\n";
    
    for (size_t i = 0; i < input_data.size(); ++i) {
        report << "原始: " << input_data[i] << "\n";
        report << "处理后: " << processed_data[i] << "\n";
        report << "哈希值: " << hash_map[processed_data[i]] << "\n\n";
    }
    
    std::string report_content = report.str();
    
    // 4. 保存报告
    std::string report_filename = "code_helper_report.txt";
    bool save_success = CodeHelper::write_file(report_filename, report_content);
    EXPECT_TRUE(save_success);
    
    // 5. 验证报告内容
    std::string read_report = CodeHelper::read_file(report_filename);
    EXPECT_EQ(read_report, report_content);
    
    // 6. 验证处理结果
    EXPECT_EQ(processed_data.size(), input_data.size());
    EXPECT_EQ(processed_data[0], "function_name_1");
    EXPECT_EQ(processed_data[1], "class_name2");
    EXPECT_EQ(processed_data[2], "constant_value");
    
    // 7. 清理
    if (std::filesystem::exists(report_filename)) {
        std::filesystem::remove(report_filename);
    }
    
    std::cout << "完整工作流程测试完成:" << std::endl;
    std::cout << "- 处理了 " << input_data.size() << " 个代码标识符" << std::endl;
    std::cout << "- 生成了 " << hash_map.size() << " 个哈希值" << std::endl;
    std::cout << "- 创建并验证了处理报告" << std::endl;
} 